import { DateRange } from '$/client'
import router from '@/router'
import moment from 'moment'
import 'moment/dist/locale/zh-cn'
import type { TableExposed } from 'vexip-ui'

export const $date = {
  get currentWeekDateRange() {
    moment.updateLocale('zh-cn', { week: { dow: 5 } })
    return DateRange.inst({
      start: moment().subtract(8, 'hour').startOf('week').hour(8).valueOf(),
      end: moment().subtract(8, 'hour').endOf('week').hour(7).add(1, 'day').valueOf()
    })
  },

  get currentMonthDateRange() {
    return DateRange.inst({
      start: moment().startOf('month').valueOf(),
      end: moment().endOf('month').valueOf()
    })
  },

  get currentDayDateRange() {
    return DateRange.inst({
      start: moment().startOf('day').valueOf(),
      end: moment().endOf('day').valueOf()
    })
  }
}

export function getDateLabel(timestamp: number, format: string = 'lll') {
  return moment(timestamp).format(format)
}

export function queryAsString<T extends string>(query: string, defaultValue?: T) {
  const result = router.currentRoute.value.query[query] as T
  if (!result && defaultValue) return defaultValue
  return result
}

export function queryAsInt(query: string, defaultValue?: number): number {
  const result = parseInt(router.currentRoute.value.query[query] as string)
  if (isNaN(result) && defaultValue) return defaultValue
  return result
}

export function rowOptions(array: string[]) {
  return array.map((x) => ({
    label: x,
    value: x
  }))
}

export function tableToSelections<T = any>(table?: TableExposed): T[] {
  return table?.getSelected() ?? []
}

export function tableToSelectionIds(table?: TableExposed): number[] {
  return (table?.getSelected() ?? []).map((x) => x.id)
}
